package com.yzf.demo.demo.Thread;


import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by 于占峰 on 2020/4/1/001.
 */
public class AtomicDemo1 {
    //定义一个成员变量
    //public static int count = 0;

    //定义一个AtomicIntger 可以保证原子性
    private static AtomicInteger count = new AtomicInteger(0);

    //定义一个方法
    public static void incr() {
        try {
            //使线程睡眠1毫秒,这样可以模拟出线程来回调度切换
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //count++;(只会由一个线程来执行)
        count.incrementAndGet();
    }

    public static void main(String[] args) throws InterruptedException {
        //构建1000个线程来调用incr方法
        for (int i = 0; i < 1000; i++) {
            new Thread(AtomicDemo::incr).start();
        }
        //设置睡眠,因为线程是异步的,这样所有线程都能执行完毕main主线程才结束
        //Thread.sleep(4000);
        //最终的执行结果一定是1000
        System.out.println(count.get());
    }
}
